package com.share.finance.risk.rules.config;

import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

/**
 * DroolsConfig是单容器模式
 * <p>
 * 规则引擎配置类--- 规则drl文件如果配置错误，那么应用是无法启动的，错误信息也很奇怪
 */
@Slf4j
//@Configuration
public class DroolsConfig {
    //指定规则文件存放的目录
    private static final String RULES_PATH = "rules/";
    private final KieServices kieServices = KieServices.Factory.get();

    @Bean
    public KieFileSystem kieFileSystem() {
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = new Resource[0];
        try {
            resources = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "*.*");
        } catch (IOException e) {
            log.info("drools加载配置异常", e);
            throw new RuntimeException(e);
        }

        String path = null;
        for (Resource resource : resources) {
            path = RULES_PATH + resource.getFilename();
            log.info("正在加载drl文件path={}", path);
            kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
        }
        return kieFileSystem;
    }

    @Bean
    public KieContainer kieContainer(@Autowired KieFileSystem kieFileSystem) {
        KieRepository kieRepository = kieServices.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
    }

    @Bean
    public KieBase kieBase(@Autowired KieContainer kieContainer) {
        return kieContainer.getKieBase();
    }

    @Bean
    public KieSession kieSession(@Autowired KieBase kieBase) {
        return kieBase.newKieSession();
    }
}
